package cn.sunxinao.pm.binary;

import cn.sunxinao.pm.models.AbstractPet;
import cn.sunxinao.pm.models.AbstractUser;
import cn.sunxinao.pm.utils.IReadWriteTool;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("unchecked")
public class ReadWriteTool implements IReadWriteTool {
    @Override
    public List<AbstractPet> readAllPets(File file) {
        if (!file.exists() || file.length() == 0) saveAllPets(new ArrayList<>(), file);
        try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file))) {
            return (List<AbstractPet>) objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            System.err.println("提示: 无法访问文件，数据可能无法保存");
            return null;
        }
    }

    @Override
    public boolean saveAllPets(List<AbstractPet> pets, File file) {
        try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(file))) {
            objectOutputStream.writeObject(pets);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("提示: 无法访问文件，数据可能无法保存");
            return false;
        }
    }

    @Override
    public List<AbstractUser> readAllUsers(File file) {
        if (!file.exists() || file.length() == 0) saveAllUsers(new ArrayList<>(), file);
        try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file))) {
            return (List<AbstractUser>) objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            System.err.println("提示: 无法访问文件，数据可能无法保存");
            return null;
        }
    }

    @Override
    public boolean saveAllUsers(List<AbstractUser> users, File file) {
        try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(file))) {
            objectOutputStream.writeObject(users);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("提示: 无法访问文件，数据可能无法保存");
            return false;
        }
    }
}
